package com.baohulu.baohulu.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.baohulu.baohulu.MyApplication;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 用于保存 cookie 的拦截器
 */
public class SaveCookiesInterceptor implements Interceptor {
    private static final String TAG = "SaveCookiesInterceptor";


    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (!response.headers("set-cookie").isEmpty()) {
            List<String> cookies = response.headers("set-cookie");
            String cookie = encodeCookie(cookies);
            saveCookie(request.url().host(), cookie);
        }
        return response;
    }

    /**
     * 整合cookie 为唯一字符串
     *
     * @param cookies cookies
     * @return cookies:[PHPSESSID=u2qtkc5m4mjjb2vqls95759nn7; path=/]
     */
    private String encodeCookie(List<String> cookies) {
        StringBuilder sb = new StringBuilder();
        Set<String> set = new HashSet<>();
        for (String cookie : cookies) {
            String[] arr = cookie.split(";");
            for (String s : arr) {
                if (set.contains(s))
                    continue;
                set.add(s);
            }
        }
        for (String cookie : set) {
            sb.append(cookie).append(";");
        }
        sb.deleteCharAt(sb.lastIndexOf(";"));
        return sb.toString();

    }


    private void saveCookie(String host, String cookie) {
        SharedPreferences.Editor editor = MyApplication.getAppContext()
                .getSharedPreferences(HttpUtil.COOKIE_PREF, Context.MODE_PRIVATE)
                .edit();

        if (!TextUtils.isEmpty(host)) {
            Log.d(TAG, "saveCookie: host=" + host + ",cookieStr=" + cookie);
            editor.putString(host, cookie);
        }
        editor.apply();
    }
}
